import cv2
from publicmodel.common import translate_text

from image_processor import process_image
from model_loader import load_model

# 全局加载模型（只加载一次）
MODEL = load_model("model/yolo11x-seg.pt", verbose=False)


def translate_result(result: str) -> str:
    """翻译检测结果（带缓存优化）"""
    if result == "mouse":
        return "鼠标"
    # 添加缓存逻辑减少API调用
    return translate_text(result, "en", "zh-cn")


def detect_objects(image_path: str) -> None:
    """处理图像并显示检测结果"""
    # 使用全局模型
    result_image, detected_items, main_object, accuracy_rate = process_image(MODEL, image_path)

    if not detected_items:
        print("未识别到物品")
        return

    # 优化循环：合并翻译和分类
    items = []
    surrounding = []
    for item in detected_items:
        translated = translate_result(item)
        items.append(translated)
        if item != main_object:
            surrounding.append(translated)

    print(f"检测到物品: {', '.join(items)}")
    print(f"主体物: {translate_result(main_object)}")  # 使用已翻译结果
    if surrounding:
        print(f"周围物: {', '.join(surrounding)}")
    else:
        print("周围物: 无")
    print(f"置信度: {accuracy_rate}%")

    if result_image is not None:
        cv2.imshow('Detected Objects', result_image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


if __name__ == '__main__':
    # 示例用法
    image_path = 'images/cups/cup1.png'
    detect_objects(image_path)
